//
//  SetViewController.m
//  EggSteward
//
//  Created by 王道林 on 16/9/7.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "SetViewController.h"
#import "BaseTableView.h"
#import "DLMacro.h"
#import "BaseView.h"
#import "BaseButton.h"
#import "Masonry.h"
#import "SetTableViewCellO.h"
#import "SetTableViewCellT.h"
#import "PersonalInfo_ViewController.h"
#import "MyInsureViewController.h"
#import "AllPowerViewController.h"
#import "NewsPushViewController.h"
#import "FeedBackViewController.h"
#import "AboutUsViewController.h"
#import "DLClearCache.h"
#import "SetLogonViewController.h"
#import "DLWNetworkingParser.h"

@interface SetViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) UIImageView *imageViewPhoto;
@property (nonatomic, strong) BaseLabel *lableEgg;
@property (nonatomic, strong) BaseButton *ButtonSingIn;
@property (nonatomic, strong) NSArray *arrData;
@property (nonatomic, strong) BaseLabel *lableName;

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    _arrData = [NSArray arrayWithObjects:@"我的投保",@"黑名单", @"夜间模式", @"消息推送设置",@"意见反馈", @"关于我们", @"清除缓存", nil];
     [self createTableview];
}
// 判读是否登录然后push界面
- (void)judgeLogon
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *ticket = [userDefault valueForKey:@"ticket"];
    NSString *uid = [userDefault valueForKey:@"uid"];
    if (ticket == nil && uid == nil)
    {
        SetLogonViewController *setLogonVC = [[SetLogonViewController alloc] init];
        [self.navigationController pushViewController:setLogonVC animated:NO];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
//    [self judgeLogon];
    [super viewWillAppear:animated];
    // bar的背景色
    self.navigationItem.title = @"设置";
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.202 green:0.851 blue:0.364 alpha:1.000];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:nil];
    self.tabBarController.tabBar.hidden = NO;
    
    // 设置网络请求来的数据
    // 网络获取积分数据
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *ticket = [userDefault valueForKey:@"ticket"];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:ticket,@"ticket", nil];
    
    [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/v1/Score/getScores" par:dic success:^(id responseObject) {
        NSString *eggNumber = [NSString stringWithFormat:@"积蛋  %@",responseObject[@"data"][@"score"]];
        _lableEgg.text = eggNumber;
    } filed:^(NSError *error) {
        
    }];
    // 获取是否签到了
    [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/v1/Score/sign_pd" par:dic success:^(id responseObject) {
        
        NSString *msg = responseObject[@"msg"];
        if ([msg isEqualToString:@"今天已经签到"]) {
            [_ButtonSingIn setTitle:@"已经签到" forState:UIControlStateNormal];
            [_ButtonSingIn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
        else
        {
            [_ButtonSingIn setTitle:@"点击签到" forState:UIControlStateNormal];
            [_ButtonSingIn setTitleColor:[UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000] forState:UIControlStateNormal];
        }
    } filed:^(NSError *error) {
        
    }];

}


#pragma mark - 创建tableview
- (void)createTableview
{
    _tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, self.view.frame.size.height - 64 - 49) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.bounces = NO;
    [self.view addSubview:_tableView];
    // 注册
    [_tableView registerClass:[SetTableViewCellO class] forCellReuseIdentifier:@"reuse"];
    [_tableView registerClass:[SetTableViewCellT class] forCellReuseIdentifier:@"reuseT"];
    [self createTableViewHeader];
    [self createTableViewFooter];
}


#pragma mark -tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        SetTableViewCellT *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseT" forIndexPath:indexPath];
        cell.labelTitle.text = _arrData[indexPath.row];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        BOOL is = [userDefault boolForKey:@"night"];
        if (is == YES) {
            cell.switchDelete.on = YES;
        } else
        {
            cell.switchDelete.on = NO;
        }
        // block的实现部分
        cell.BlockOn = ^(BaseSwitch *switchDe)
        {
            
        };
        cell.BlockOff = ^(BaseSwitch *switchDe)
        {
            
        };
        return cell;
    } else
    {
    SetTableViewCellO *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    cell.labelTitle.text = _arrData[indexPath.row];
    return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


#pragma mark - 创建tableView的头视图
- (void)createTableViewHeader
{
    BaseView *BackView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 220)];
    BackView.backgroundColor = [UIColor colorWithRed:0.202 green:0.851 blue:0.364 alpha:1.000];
    // 移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:BackView name:@"day" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:BackView name:@"night" object:nil];

    _tableView.tableHeaderView = BackView;
    // 头像
    // 读取 本地的图片
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString *pathdata = [[pathArray lastObject] stringByAppendingPathComponent:@"iamgedate"];
    NSData *iamgeData = [NSData dataWithContentsOfFile:pathdata];
    UIImage *iamge = [UIImage imageWithData:iamgeData];
    if (iamge == nil) {
    
        _imageViewPhoto = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Davatar"]];
    } else
    {
        _imageViewPhoto = [[UIImageView alloc] initWithImage:iamge];
    }
    
    _imageViewPhoto.layer.masksToBounds = YES;
    _imageViewPhoto.layer.cornerRadius = VIEW_WIDTH * 0.11;
    [BackView addSubview:_imageViewPhoto];
    [_imageViewPhoto mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(BackView.mas_top).mas_offset(20);
        make.centerX.mas_equalTo(BackView.mas_centerX);
        make.width.mas_equalTo(BackView.mas_width).multipliedBy(0.22);
        make.height.mas_equalTo(BackView.mas_width).multipliedBy(0.22);
    }];
    // 添加点击手势
    _imageViewPhoto.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_imageViewPhoto addGestureRecognizer:tap];
    
    // 下面的横条
    BaseView *viewWhite = [[BaseView alloc] init];
    [BackView addSubview:viewWhite];
    viewWhite.backgroundColor = [UIColor whiteColor];
    [viewWhite mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(BackView.mas_bottom);
        make.left.mas_equalTo(BackView.mas_left);
        make.width.mas_equalTo(BackView.mas_width);
        make.height.mas_equalTo(60);
    }];
    
    UIImageView *imageViewEgg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"jf"]];
    [viewWhite addSubview:imageViewEgg];
    
    UIImageView *imageViewSingIn = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qd"]];
    [viewWhite addSubview:imageViewSingIn];
    
    UIView *viewLine = [[UIView alloc] init];
    viewLine.backgroundColor = [UIColor grayColor];
    [viewWhite addSubview:viewLine];
    
    UIView *viewLineT = [[UIView alloc] init];
    viewLineT.backgroundColor = [UIColor grayColor];
    [viewWhite addSubview:viewLineT];
    
    _lableEgg = [[BaseLabel alloc] init];
    [viewWhite addSubview:_lableEgg];
    
    
    _ButtonSingIn = [BaseButton buttonWithType:UIButtonTypeSystem];
    [viewWhite addSubview:_ButtonSingIn];
    [_ButtonSingIn addTarget:self action:@selector(buttonSingInAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 约束
    [viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(viewWhite.mas_centerX);
        make.width.mas_equalTo(1);
        make.top.mas_equalTo(viewWhite.mas_top).mas_offset(10);
        make.bottom.mas_equalTo(viewWhite.mas_bottom).mas_offset(-10);
    }];
    
    [viewLineT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(viewWhite.mas_bottom);
        make.height.mas_equalTo(1);
        make.left.mas_equalTo(viewWhite.mas_left);
        make.right.mas_equalTo(viewWhite.mas_right);
    }];

    
    [imageViewEgg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(viewWhite.mas_centerY);
        make.height.mas_equalTo(25);
        make.centerX.mas_equalTo(viewWhite.mas_centerX).multipliedBy(0.3);
        make.width.mas_equalTo(25);
    }];
    
    [imageViewSingIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(viewWhite.mas_centerY);
        make.height.mas_equalTo(25);
        make.centerX.mas_equalTo(viewWhite.mas_centerX).multipliedBy(1.3);
        make.width.mas_equalTo(25);
    }];
    
    [_lableEgg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(viewWhite.mas_centerY);
        make.height.mas_equalTo(25);
        make.left.mas_equalTo(imageViewEgg.mas_right).mas_offset(10);
        make.right.mas_equalTo(viewLine.mas_right).mas_offset(-10);
    }];
    
    [_ButtonSingIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(viewWhite.mas_centerY);
        make.height.mas_equalTo(25);
        make.left.mas_equalTo(imageViewSingIn.mas_right).mas_offset(10);
        make.width.mas_equalTo(70);
    }];
    
    // 头像下面的昵称
    _lableName = [[BaseLabel alloc] init];
    _lableName.textColor = [UIColor whiteColor];
    _lableName.font = [UIFont systemFontOfSize:20];
    _lableName.textAlignment = 1;
    _lableName.text = @"王道";
    [BackView addSubview:_lableName];
    [_lableName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_imageViewPhoto.mas_bottom).mas_offset(10);
        make.centerX.mas_equalTo(BackView.mas_centerX);
        make.width.mas_equalTo(BackView.mas_width).multipliedBy(0.5);
        make.height.mas_equalTo(35);
    }];
    
}
#pragma mark -创建tableView的尾视图
- (void)createTableViewFooter
{
    BaseView *view = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 80)];
    view.backgroundColor = [UIColor whiteColor];
    _tableView.tableFooterView = view;
    
    BaseButton *button = [BaseButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"退出登录" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor colorWithRed:0.838 green:0.008 blue:0.016 alpha:1.000];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:20];
    [view addSubview:button];
    button.frame = CGRectMake(10, 10, VIEW_WIDTH - 20, 50);
    
    [button addTarget:self action:@selector(buttonExitAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonExitAction:(BaseButton *)button
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault removeObjectForKey:@"ticket"];
    [userDefault removeObjectForKey:@"uid"];
    SetLogonViewController *setLogonVC = [[SetLogonViewController alloc] init];
    [self.navigationController pushViewController:setLogonVC animated:YES];
}
#pragma mark -点击头像的手势
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    PersonalInfo_ViewController *PerVC = [[PersonalInfo_ViewController alloc] init];
    [self.navigationController pushViewController:PerVC animated:YES];
}

#pragma mark - cell的点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        MyInsureViewController *myInsureVC = [[MyInsureViewController alloc] init];
        [self.navigationController pushViewController:myInsureVC animated:YES];
    } else if (indexPath.row == 1)
    {
        AllPowerViewController *allVC = [[AllPowerViewController alloc] init];
        allVC.navigationTitle = @"黑名单";
        allVC.contectTiltle = @"暂无黑名单";
        [self.navigationController pushViewController:allVC animated:YES];
    } else if (indexPath.row == 2)
    {
        SetTableViewCellT *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.switchDelete.on = !cell.switchDelete.on;
        if (cell.switchDelete.on) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"night" object:nil userInfo:nil];
             NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault removeObjectForKey:@"night"];
            [userDefault setBool:YES forKey:@"night"];
        } else
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"day" object:nil userInfo:nil];
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault removeObjectForKey:@"night"];
            [userDefault setBool:NO forKey:@"night"];
        }
     
    } else if (indexPath.row == 3)
    {
        NewsPushViewController *newsPushVC = [[NewsPushViewController alloc] init];
        [self.navigationController pushViewController:newsPushVC animated:YES];
    }
    else if (indexPath.row == 4)
    {
        FeedBackViewController *feedBackVC = [[FeedBackViewController alloc] init];
        [self.navigationController pushViewController:feedBackVC animated:YES];
    } else if (indexPath.row == 5)
    {
        AboutUsViewController *aboutVC = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
    } else
    {
        // 清除缓存
        DLClearCache *clearCache = [DLClearCache clearCache];
        NSString *stringCache = [clearCache CalculateCache];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否清除缓存" message:stringCache preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *actionClear = [UIAlertAction actionWithTitle:@"清除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
           NSString *clearLate = [clearCache ClearCacheAndCalculateNew];
            alertController.message = clearLate;
        }];
        [alertController addAction:actionCancel];
        [alertController addAction:actionClear];
        [self presentViewController:alertController animated:YES completion:^{
            
        }];
    }
}

#pragma mark - 点击cell的时候有颜色显示
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    SetTableViewCellO *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:0.886 green:1.000 blue:0.066 alpha:1.000];
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    SetTableViewCellO *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}

#pragma mark - 签到的button

- (void)buttonSingInAction:(BaseButton *)button
{
   if ([button.titleLabel.text isEqualToString:@"点击签到"])
   {
       NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
       NSString *ticket = [userDefault valueForKey:@"ticket"];
       NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:ticket,@"ticket", nil];
       [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/v1/Score/sign" par:dic success:^(id responseObject) {
           
           NSString *msg = responseObject[@"msg"];
           
        if ([msg isEqualToString:@"签到成功"]) {
               [button setTitle:@"已经签到" forState:UIControlStateNormal];
               [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            //获取总积分
//            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//            NSString *ticket = [userDefault valueForKey:@"ticket"];
//            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:ticket,@"ticket", nil];
            
            [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/v1/Score/getScores" par:dic success:^(id responseObject) {
                NSString *eggNumber = [NSString stringWithFormat:@"积蛋  %@",responseObject[@"data"][@"score"]];
                _lableEgg.text = eggNumber;
            } filed:^(NSError *error) {
                
            }];

           }
       } filed:^(NSError *error) {
           
       }];

   }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
